﻿using CommunityToolkit.Mvvm.ComponentModel;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using Autodesk.Revit.DB.Mechanical; // 需要 Space
using Autodesk.Revit.DB;

namespace RevitProject.SpaceManager.ViewModel.SpaceViewModel
{
    public partial class SpaceTypeTreeNodeViewModel : ObservableObject
    {
        private string _displayName;
        public string DisplayName { get => _displayName; set => SetProperty(ref _displayName, value); }

        private bool _isExpanded;
        public bool IsExpanded { get => _isExpanded; set => SetProperty(ref _isExpanded, value); }

        private bool _isSelected;
        public bool IsSelected { get => _isSelected; set => SetProperty(ref _isSelected, value); }

        //用于判断叶节
        public bool IsLeafNode => Children == null || Children.Count == 0;

        private int _totalSpaceCount;
        public int TotalSpaceCount
        {
            get => _totalSpaceCount;
            internal set => SetProperty(ref _totalSpaceCount, value);
        }

        // 让 AssociatedSpaceTypeId 可写（或者用构造函数赋值后不再变）---
        // 这个 ID 代表此节点（如果是叶节点）对应的 Revit HVACLoadSpaceType 的 ElementId
        // 非叶节点此 ID 通常为 InvalidElementId
        private ElementId _associatedSpaceTypeId = ElementId.InvalidElementId;
        public ElementId AssociatedSpaceTypeId
        {
            get => _associatedSpaceTypeId;
            // Internal set 允许在 ViewModel 内部逻辑中设置它
            internal set => SetProperty(ref _associatedSpaceTypeId, value);
        }
        // 标识是否为代表所有空间的根节点
        public bool IsAllSpacesNode { get; set; } = false;
        // 标识是否为代表未指定类型的节点
        public bool IsUnassignedTypeNode { get; set; } = false;


        public ObservableCollection<SpaceTypeTreeNodeViewModel> Children { get; set; } = new ObservableCollection<SpaceTypeTreeNodeViewModel>();
        public List<Space> AssociatedSpaces { get; set; } = new List<Space>(); // 直接关联到此节点的 Space 列表
        public SpaceTypeTreeNodeViewModel Parent { get; set; }

        // 构造函数
        public SpaceTypeTreeNodeViewModel(string displayName, ElementId spaceTypeId, SpaceTypeTreeNodeViewModel parent = null)
        {
            DisplayName = displayName;
            AssociatedSpaceTypeId = spaceTypeId; // 存储关联的类型ID
            Parent = parent;
            IsExpanded = false;
            IsSelected = false;
            _totalSpaceCount = 0;
        }

        // 递归获取此节点及其所有子孙节点关联的空间列表
        public List<Space> GetAllSpacesInChildren()
        {
            List<Space> allSpaces = new List<Space>();
            if (IsAllSpacesNode) // 特殊处理“全部空间”
            {
                return new List<Space>(AssociatedSpaces);
            }

            allSpaces.AddRange(AssociatedSpaces); // 添加自身的

            // 递归添加子节点的
            foreach (var child in Children)
            {
                allSpaces.AddRange(child.GetAllSpacesInChildren());
            }
            return allSpaces;
        }
    }
}